<?php
/*
 * Create a new user.
 */

// check that we have the necessary parameters
if (!F3::exists('POST.email') || !F3::exists('POST.password') || strlen(F3::get('POST.email')) < 5 || strlen(F3::get('POST.password')) < 4)
{
  // we need at least email and password
  header('HTTP/1.1 500 Internal Server Error');
  header("Content-Type: application/json");
  $err = array("error_message" => "Need at least two parameters: email and password.");
  echo json_encode($err);
  return;
}

// check that the email is unique (technically, the following insert might still fail,
// if a race condition occurs)
$param = array('1' => F3::get('POST.email'));
$res = DB::sql("SELECT COUNT(*) AS c FROM users WHERE email = ?", $param);
$row = $res[0];
$count = $row['c'];
if ($count > 0)
{
  // email address already exists
  header('HTTP/1.1 500 Internal Server Error');
  header("Content-Type: application/json");
  $err = array("error_message" => "User with this email address already exists.");
  echo json_encode($err);
  return;
}

// hash password
// base-2 logarithm of the iteration count used for password stretching
$hash_cost_log2 = 8;
// make hashes non-portable to older systems
$hash_portable = FALSE;
// get hasher
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
// hash password
$hash = $hasher->HashPassword(F3::get('POST.password'));
if (strlen($hash) < 20)
{
  // could not hash password
  header('HTTP/1.1 500 Internal Server Error');
  header("Content-Type: application/json");
  $err = array("error_message" => "Internal error.");
  echo json_encode($err);
  return;
}
unset($hasher);

// create new user
$param = array('1' => F3::get('POST.email'), '2' => $hash);
$res = DB::sql("INSERT INTO users(email, password) VALUES(?, ?)", $param);
$id = 0;
$db = F3::get('DB');
$pdo = $db->pdo;
$id = $pdo->lastInsertId();

// update fields, if necessary
$fields = array('fname', 'lname', 'nickname');
foreach ($fields as $field)
{
  if (F3::exists("POST.$field"))
  {
    // optional field exists, update user
    $param = array('1' => F3::get("POST.$field"), '2' => $id);
    DB::sql("UPDATE users SET $field = ? WHERE id = ?", $param);
  }
}

header('HTTP/1.1 201');
header("Content-Type: application/json");
echo json_encode(array("success" => "1", "user_id" => $id));

?>
